/** ****************************************************************************
@defgroup DIMMER Dimmer
@ingroup BSP_External
@brief 调光器驱动
@addtogroup Dimmer
@{
*******************************************************************************/

#ifndef _DIMMER_H_
#define _DIMMER_H_

#include "nonos.h"
#include "switch.h"

/// 开关类(如LED/继电器) 驱动
typedef struct {
	FUNC_GPIO_PwmSetDuty funcPwmSetDuty;///< GPIO 驱动函数: 修改 PWM 占空比
	uint8_t duty;							///< PWM 当前占空比: 0~99%
    OSTaskId blinkTaskId;				///< 闪烁任务ID
    uint32_t blinkExOnTime;    				///< 闪烁亮的时间
} driver_dimmer_t;

/**
 * @brief 初始化
 * @param dev 驱动数据结构指针
 * @param funcPwmSetDuty GPIO 驱动函数: 修改 PWM 占空比
 */
void dimmer_init(driver_dimmer_t* dev, FUNC_GPIO_PwmSetDuty funcPwmSetDuty);

/// @brief 取得当前状态
inline static uint8_t dimmer_state(driver_dimmer_t* dev) { if(!dev) { return 0; } return dev->duty; }

/// @brief SWITCH 亮
/// @return 状态是否变化了
inline static bool dimmer_dimTo(driver_dimmer_t* dev, uint8_t duty) { if(!dev) { return false; } dev->duty = duty; dev->funcPwmSetDuty(duty); return true; }

/// @brief SWITCH 亮
/// @return 状态是否变化了
inline static bool dimmer_on(driver_dimmer_t* dev) { if(!dev) { return false; } dimmer_dimTo(dev, 100); return true; }

/// @brief SWITCH 灭
/// @return 状态是否变化了
inline static bool dimmer_off(driver_dimmer_t* dev) { if(!dev) { return false; } dimmer_dimTo(dev, 0); return true; }

/// @brief SWITCH 状态反转
inline static void dimmer_toggle(driver_dimmer_t* dev) { if(!dev) { return; } dev->duty ? dimmer_off(dev) : dimmer_on(dev); }

/// @brief 开关到指定状态
/// @param state: 0-OFF; 1-ON; 0xFF-REVERSE;
/// @return 状态是否变化了
bool dimmer_switchTo(driver_dimmer_t* dev, switch_state_t state, uint32_t keepTime1, uint32_t keepTime2, uint8_t flashTimes);

/// @brief 闪一下
/// @param time: 保持时间, ms
void dimmer_blink(driver_dimmer_t* dev, uint16_t time);

/// @brief 闪多下
/// @param onTime: 点亮时间, ms
/// @param offTime: 关闭时间, ms
/// @param count: 闪几次；=OSTASK_REPEAT_FOREVER 表示永远闪烁
/// @retval task, 可通过 osTaskKill() 来停止闪烁
OSTaskId dimmer_blinkEx(driver_dimmer_t* dev, uint16_t onTime, uint16_t offTime, uint16_t count);

/// @brief 停止闪烁
inline static void dimmer_blinkStop(driver_dimmer_t* dev) { if(!dev) { return; } osTaskDestroy(dev->blinkTaskId); }


#endif  // _SWITCH_H_
/// @}
